//
//  DUListLoader.m
//  toutiao
//
//  Created by duyujin1 on 2021/7/26.
//

#import "DUListLoader.h"
//#import <AFNetworking.h>
#import "DUListItem.h"

@implementation DUListLoader

-(void)loadListDataWithFinishBlock:(DUListLoaderFinishBlock)finishBlock isRefresh:(BOOL)isRefresh{
    
//    [[AFHTTPSessionManager manager] GET:@"https://static001.geekbang.org/univer/classes/ios_dev/lession/45/toutiao.json" parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"");
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"");
//    }];
    
    if(!isRefresh){
        //先从本地找
        NSArray<DUListItem *> *listdata=[self _readDataFormLocal];
        if(listdata){
            finishBlock(YES,listdata);
        }
    }
    
    //再发送网络请求，通过返回来的数据更新列表（直接替换）
    NSString * urlString=@"http://c.m.163.com/nc/article/headline/T1348649580692/0-40.html";
    NSURL * listURL=[NSURL URLWithString:urlString];

    //__unused NSURLRequest * listRequest=[NSURLRequest requestWithURL:listURL];

    NSURLSession * session=[NSURLSession sharedSession];


    __weak typeof(self) weakSelf=self;
    NSURLSessionDataTask * dataTask=[session dataTaskWithURL:listURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        __strong typeof (weakSelf) strongSelf=weakSelf;
        NSError * jsonError;
        id jsonObj=[NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];

    #warning 类型检查
        NSArray * dataArray=[((NSDictionary *) jsonObj) objectForKey:@"T1348649580692"];
        NSMutableArray * listItemArray=@[].mutableCopy;
        for(NSDictionary *info in dataArray){
            DUListItem * listItem=[[DUListItem alloc] init];
            [listItem configWithDictionary:info];
            [listItemArray addObject:listItem];
        }
        [strongSelf _archiveListDataWithArray:listItemArray.copy];

        dispatch_async(dispatch_get_main_queue(), ^{
            if(finishBlock){
                finishBlock(error==nil,listItemArray.copy);
            }
        });
    }];
    [dataTask resume];
}

-(NSArray<DUListItem *> *)_readDataFormLocal{
    //获取本地文件路径
    NSArray * pathArray=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString * cachePath=[pathArray firstObject];
    NSString * listDataPath=[cachePath stringByAppendingPathComponent:@"DUData/list"];
    //读取文件内容
    NSFileManager * fileManager=[NSFileManager defaultManager];
    NSData *  readListData=[fileManager contentsAtPath:listDataPath];
    //将存储的二进制文件转换为目标数据
    id unarchiveObj=[NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithObjects:[NSArray class],[DUListItem class],nil] fromData:readListData error:nil];
    
    if([unarchiveObj isKindOfClass:[NSArray class]] &&[unarchiveObj count]>0){
        return (NSArray<DUListItem *> *)unarchiveObj;
    }
    return nil;
}

-(void)_archiveListDataWithArray:(NSArray<DUListItem *> *)array{
    //获取系统沙盒目录cache文件夹
    NSArray * pathArray=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString * cachePath=[pathArray firstObject];
    //单例
    NSFileManager * fileManager=[NSFileManager defaultManager];
    
    //创建文件夹
    NSString * dataPath=[cachePath stringByAppendingPathComponent:@"DUData"];
    NSError * creatError;
    [fileManager createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&creatError];
    
    //创建文件
    NSString * listDataPath=[dataPath stringByAppendingPathComponent:@"list"];
    NSData * listData=[NSKeyedArchiver archivedDataWithRootObject:array requiringSecureCoding:YES error:nil];//序列化
    [fileManager createFileAtPath:listDataPath contents:listData attributes:nil];
    
    
    
    
    //反序列化
//    NSData * readListData=[fileManager contentsAtPath:listDataPath];
//    id unarchiveObj=[NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithObjects:[NSArray class],[DUListItem class],nil] fromData:readListData error:nil];
    
//    //key-value存储
//    [[NSUserDefaults standardUserDefaults] setValue:listData forKey:@"listData"];
//    NSData * testLiatData=[[NSUserDefaults standardUserDefaults] dataForKey:@"listData"];
//    id unarchiveObj=[NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithObjects:[NSArray class],[DUListItem class],nil] fromData:testLiatData error:nil];
    
//    //查询
//    BOOL fileExist=[fileManager fileExistsAtPath:listDataPath];
    
//    //删除
//    if(fileExist){
//        [fileManager removeItemAtPath:listDataPath error:nil];
//    }
    
//    //在listdata文件后插入“def”
//    NSFileHandle * fileHandle=[NSFileHandle fileHandleForUpdatingAtPath:listDataPath];
//    [fileHandle  seekToEndOfFile];
//    [fileHandle writeData:[@"def" dataUsingEncoding:NSUTF8StringEncoding]];
//
//    //实时更新文件
//    [fileHandle synchronizeFile];
//    [fileHandle closeFile];
}

@end
